<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { getCategory } from "@/service/category";
import type { Category } from "@/types/category";
import type { Good, GoodModify } from "@/types/good";
import { getGoods, addGood, updateGood, delGood } from "@/service/good";
import Compressor from "compressorjs";
import { h } from "vue";
import {
  Image,
  Message,
  Modal,
  type FormInstance,
  type TableColumnData,
  Button,
} from "@arco-design/web-vue";
import { storeToRefs } from "pinia";
import { useUserStore } from "@/store/user";
// 查询条件
const filters = reactive({
  name: "",
  type: "",
});

// 下拉类别列表
const categories = ref<Category[]>([]);
// 表格数据
const goods = ref<Good[]>([]);
// 加载状态
const loading = ref(false);

// 表格列定义
const columns = <TableColumnData[]>[
  { title: "序号", render: ({ rowIndex }) => `${rowIndex + 1}` },
  { title: "名称", dataIndex: "name", width: 140 },
  {
    title: "类别",
    dataIndex: "type",
    width: 80,
  },
  { title: "价格（元）", dataIndex: "price", width: 140 },
  { title: "材质", dataIndex: "material" },
  { title: "规格", dataIndex: "size" },
  {
    title: "货品图片",
    dataIndex: "img",
    render: (row: any) => {
      return h(Image, {
        width: 80,
        src: "/api/file/" + row.record.img,
      });
    },
  },
  { title: "描述", dataIndex: "description" },
  {
    title: "操作",
    width: 160,
    render: (row: any) => {
      return h("div", [
        h(
          Button,
          {
            onClick: () => onOpenModal("编辑", row.record),
          },
          () => "编辑"
        ),
        h(
          Button,
          {
            style: { marginLeft: "8px" },
            status: "danger",
            onClick: () => handleDel(row.record.id),
          },
          () => "删除"
        ),
      ]);
    },
  },
];

// 获取类别选项
const fetchCategories = () => {
  try {
    getCategory({ page: 1, pageSize: 100 }).then((res) => {
      categories.value = res.data.list;
    });
  } catch (e) {
    console.error("加载类别失败", e);
  }
};
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
});

const handlePageChange = (page: number) => {
  pagination.page = page;
  fetchGoods();
};

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize;
  pagination.page = 1;
  fetchGoods();
};
// 获取表格数据
const fetchGoods = () => {
  loading.value = true;
  try {
    getGoods({
      ...filters,
      page: pagination.page,
      pageSize: pagination.pageSize,
    }).then((res) => {
      goods.value = res.data.list;
      pagination.total = res.data.total;
    });
  } catch (e) {
    console.error("加载货品失败", e);
  } finally {
    loading.value = false;
  }
};

// 查询
const onSearch = () => {
  fetchGoods();
};

// 重置
const onReset = () => {
  filters.name = "";
  filters.type = "";
  fetchGoods();
};

onMounted(() => {
  fetchCategories();
  fetchGoods();
});

const modalVisiable = ref(false);
const cId = ref<number>();
const onOpenModal = (type: string, row?: Good) => {
  formRef.value?.clearValidate();
  formRef.value?.resetFields();
  modalForm.name = "";
  modalForm.description = "";
  modalForm.type = "";
  modalForm.price = undefined;
  modalForm.img = "";
  modalForm.material = "";
  modalForm.size = "";
  modalTitle.value = type;
  fileList.value = [];
  if (type === "编辑") {
    if (!row) return;
    modalForm.name = row.name;
    modalForm.description = row.description;
    modalForm.type = row.type;
    modalForm.price = row.price;
    modalForm.img = row.img;
    modalForm.material = row.material;
    modalForm.size = row.size;
    fileList.value = [
      {
        uid: row.id,
        name: row.img,
        status: "done",
        url: "/api/file/" + row.img,
      },
    ];
    cId.value = row.id;
    console.log(cId.value);
  } else {
    cId.value = undefined;
  }
  modalVisiable.value = true;
};
const modalTitle = ref("新增");

const handleCancelModal = () => {
  modalVisiable.value = false;
};
const handleOkModal = () => {
  formRef.value?.validate().then((r: any) => {
    if (r) return;
    const isAdd = modalTitle.value === "新增";
    const action = isAdd
      ? addGood({
          ...modalForm,
        })
      : updateGood({ ...modalForm, id: cId.value });
    action.then((res) => {
      Message.success(res.message);
      onSearch();
      modalVisiable.value = false;
    });
  });
};

const handleDel = (id: number) => {
  Modal.confirm({
    title: "删除确认",
    content: "确定要删除该商品吗？",
    onOk: () => {
      delGood(id).then((res) => {
        Message.success(res.message);
        onSearch();
      });
    },
  });
};

const modalForm = reactive(<GoodModify>{
  name: "",
  type: "",
  description: "",
  material: "",
  size: "",
  price: undefined,
  img: "",
});

const rules = {
  name: [{ required: true, message: "请输入货品名称" }],
  type: [{ required: true, message: "请选择货品类别" }],
  price: [{ required: true, message: "请输入货品价格" }],
  img: [{ required: true, message: "请上传货品图片" }],
};

const formRef = ref<FormInstance>();
const fileList = ref<any[]>([]);
const { userCredit } = storeToRefs(useUserStore());

const onBeforeUpload = (file: File): Promise<File> => {
  return new Promise<File>((resolve, reject) => {
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      Message.error("图片必须小于2MB!");
      reject(false);
      return;
    }
    new Compressor(file, {
      quality: 0.8, // 压缩质量
      maxWidth: 1200, // 最大宽度
      maxHeight: 1200, // 最大高度
      success(result) {
        const newFile = new File([result], file.name, {
          type: result.type,
          lastModified: Date.now(),
        });
        resolve(newFile);
      },
      error(err) {
        console.error("图片压缩失败:", err);
        Message.error("图片压缩失败，请重试");
        reject(false);
      },
    });
  });
};

const handleUploadSuccess = (res: any) => {
  modalForm.img = res.response.data.uuid;
};
</script>

<template>
  <div class="good-page">
    <!-- 查询区域 -->
    <a-card class="search-card">
      <a-form :model="filters" layout="inline">
        <a-form-item label="货品名称">
          <a-input
            v-model="filters.name"
            placeholder="请输入货品名称"
            style="width: 200px"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="货品类别">
          <a-select
            v-model="filters.type"
            placeholder="请选择货品类别"
            allow-clear
            style="width: 200px"
          >
            <a-option v-for="cat in categories" :key="cat.id" :value="cat.name">
              {{ cat.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button @click="onOpenModal('新增')">
            <template #icon>
              <IconPlus></IconPlus>
            </template>
            添加货品
          </a-button>
          <a-button style="margin-left: 8px" type="primary" @click="onSearch"
            >查询</a-button
          >
          <a-button style="margin-left: 8px" @click="onReset">重置</a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 表格区域 -->
    <div class="table-wrapper">
      <a-table
        :columns="columns"
        :data="goods"
        :pagination="{
          ...pagination,
          showTotal: true,
          showPageSize: true,
        }"
        :scroll="{ y: '100%' }"
        :loading="loading"
        row-key="id"
        @page-change="handlePageChange"
        @pageSize-change="handlePageSizeChange"
      />
    </div>

    <!-- 添加或编辑 -->
    <a-modal
      :visible="modalVisiable"
      :title="modalTitle"
      :ok-text="modalTitle"
      :cancel-text="'取消'"
      @ok="handleOkModal"
      @cancel="handleCancelModal"
    >
      <a-form :model="modalForm" :rules="rules" ref="formRef">
        <a-form-item label="货品名称" field="name">
          <a-input
            v-model:modelValue="modalForm.name"
            placeholder="请输入货品名称"
          ></a-input>
        </a-form-item>
        <a-form-item label="货品类别" field="type">
          <a-select
            v-model:modelValue="modalForm.type"
            placeholder="请选择货品类别"
            allow-clear
          >
            <a-option v-for="cat in categories" :key="cat.id" :value="cat.name">
              {{ cat.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item label="价格（元）" field="price">
          <a-input-number
            v-model:modelValue="modalForm.price"
            placeholder="请输入货品价格"
          ></a-input-number>
        </a-form-item>
        <a-form-item label="货品图片" field="img">
          <a-upload
            action="/api/file/upload"
            ref="uploadRef"
            @success="handleUploadSuccess"
            :on-before-upload="onBeforeUpload"
            :headers="{ Authorization: userCredit.token }"
            v-model:file-list="fileList"
            :limit="1"
          >
            <template #upload-button>
              <div class="upload-button">
                <div>
                  拖入或
                  <span style="color: #3370ff">点击选择图片上传</span>
                </div>
              </div>
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item label="材质" field="material">
          <a-input
            v-model:modelValue="modalForm.material"
            placeholder="请输入材质"
          ></a-input>
        </a-form-item>
        <a-form-item label="规格" field="size">
          <a-input
            v-model:modelValue="modalForm.size"
            placeholder="请输入规格"
          ></a-input>
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea
            placeholder="请输入货品描述"
            v-model:modelValue="modalForm.description"
            allow-clear
            style="padding-right: 40px"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped lang="less">
.good-page {
  display: flex;
  flex-direction: column;
  height: calc(100vh - (58px + 24px + 70px));
  overflow: hidden;
  .search-card {
    margin-bottom: 16px;
  }
  .table-wrapper {
    flex: 1;
    min-height: 0;
  }
}

.upload-button {
  background-color: var(--color-fill-2);
  color: var(--color-text-1);
  border: 1px dashed var(--color-fill-4);
  height: 120px;
  width: 380px;
  border-radius: 2;
  line-height: 120px;
  text-align: center;
}
</style>
